<template>
  <div class="upload_dialog" v-if="dialogVisible">
    <el-dialog
      title="上传文件"
      :visible.sync="dialogVisible"
      width="400px"
      customClass="mes_dialog "
      v-dialogDrag
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div class="step_one mes_file_secret" v-if="step === 1">
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>文档密级：</div>
          <div class=" import_cont">
            <el-select v-model="secrecyGrade" size="small" placeholder="请选择密级">
              <el-option
                v-for="item in fileSecretLevel"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="import_item">
          <div class="import_label"><span class="import_required">*</span>选择文件：</div>
          <div class=" import_cont file_cont">
            <div class="mes_btn">
              <el-button class="file_btn" @click="$refs.fileInput.click()">
                <i class="iconfont icon-btn_addnew"></i>
                <span>选择文件</span>
                <input type="file"
                       ref="fileInput"
                       class="file_input"
                       :accept="accept.toString()"
                       @change="fileChange">
              </el-button>
              <span class="accept_text">支持{{accept.join('、')}}格式</span>
            </div>
            <div class="file_name_input" v-show="fileData && fileData.name">
              <i class="el-icon-document"></i>
              <tooltip-txt :text="fileData && fileData.name"></tooltip-txt>
            </div>
          </div>
        </div>
      </div>
      <div class="step_two" v-else-if="step === 2">
        <span>文件上传中...</span>
        <div class="total_progress">
          <div class="current_progress" :style="{width: progress}">
            <span>{{progress}}</span>
          </div>
        </div>
      </div>
      <div class="step_three" v-else-if="step === 3">
        <div class="step_msg">
          <i class="iconfont icon-xiaoxitishi"></i>
          <span class="step_msg_txt">上传失败</span>
        </div>
      </div>
      <div class="step_four"
           v-else-if="step === 4"
           v-loading="true"
           element-loading-text="设备绑定中"
      ></div>
      <div class="step_five" v-else-if="step === 5">
        <div class="step_msg">
          <i class="iconfont icon-xiaoxitishi"></i>
          <span class="step_msg_txt">绑定设备失败</span>
        </div>
      </div>
      <div class="step_six" v-else-if="step === 6">
        <div class="step_msg">
          <i class="iconfont icon-zhengquetishi"></i>
          <span class="step_msg_txt">上传成功</span>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
      <el-button type="primary" v-if="step === 1" @click="importFile">上传</el-button>
      <el-button type="primary" v-else-if="step === 3" @click="handleClose(true)">重新上传</el-button>
      <el-button type="primary" v-else-if="step === 5" @click="handleClose(true)">重新上传</el-button>
      <el-button type="primary" v-else-if="step === 6" @click="handleClose">确定</el-button>
      <el-button @click="handleClose" v-if="step !== 6">取消</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'uploadDialog',
  data() {
    return {
      // 是否显示弹框
      dialogVisible: false,
      // 上传token
      importToken: null,
      // 绑定设备token
      deviceToken: null,
      // 文件对象
      fileData: {},
      // 设备ID
      deviceId: '',
      // 上传步骤
      step: 1,
      // 上传进度
      progress: '0%',
      // 文件密级
      secrecyGrade: this.defaultFileLevel,
      // 文件限制类型
      accept: ['.xls', '.xlsx']
    }
  },
  computed: {
    // 文档密级字典
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    }
  },
  methods: {
    // 打开弹框
    openDialog(id) {
      this.deviceId = id
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.fileInput.value = null
      })
    },
    // 关闭弹框
    handleClose(type) {
      switch (this.step) {
        case 1:
          this.dialogVisible = false
          this.secrecyGrade = this.defaultFileLevel
          this.clear()
          break
        case 6:
          this.dialogVisible = false
          this.$emit('uploadSuccess')
          this.secrecyGrade = this.defaultFileLevel
          this.clear()
          break
        case 3:
        case 5:
          if (type !== true) {
            this.dialogVisible = false
            this.secrecyGrade = this.defaultFileLevel
          }
          this.clear()
          break
        case 2:
          this.importToken.cancel('终止上传')
          this.step = 3
          break
        case 4:
          this.deviceToken.cancel('终止绑定')
          this.step = 5
          break
      }
    },
    // 清空重置
    clear() {
      this.deviceId = ''
      this.fileData = {}
      this.importToken = null
      this.deviceToken = null
      this.progress = '0%'
      this.step = 1
    },
    // 选择文件
    fileChange(e) {
      let file = e.target.files[0]
      if (file && /^(\.xls)|(xlsx)$/.test(file.name.slice(-4).toLowerCase())) {
        this.fileData = file
        e.target.value = null
      } else if (file) {
        this.fileData = {}
        this.$message({
          type: 'error',
          message: `文件格式错误，请选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      }
    },
    // 上传进度回调
    progressBar(progressEvent) {
      if (progressEvent.lengthComputable) {
        this.progress = parseInt(progressEvent.loaded / progressEvent.total * 100) + '%'
      }
    },
    // 点击上传
    importFile() {
      if (!this.secrecyGrade) {
        this.$message({
          type: 'error',
          message: '请先选择文档密级',
          duration: 1500,
          center: true
        })
      } else if (!this.fileData.name) {
        this.$message({
          type: 'error',
          message: `请先选择后缀为${this.accept.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      } else {
        this.step = 2
        this.importToken = this.$axios.CancelToken.source()
        let formdata = new FormData()
        formdata.append('file', this.fileData)
        formdata.append('fileSecretLevel', this.secrecyGrade)
        this.$store.dispatch('importFile', {
          data: formdata,
          onUploadProgress: this.progressBar,
          cancelToken: this.importToken.token,
        }).then(res => {
          this.step = 4
          this.saveTemplate(res.filePath)
        }).catch(() => {
          this.step = 3
        })
      }
    },
    // 上传成功回调
    saveTemplate(filePath) {
      this.deviceToken = this.$axios.CancelToken.source()
      let postData = {
        method: 'post',
        url: 'a/device/device/savetemplate',
        data: {
          path: filePath,
          fileName: this.fileData.name,
          fileSize: this.fileData.size,
          deviceId: this.deviceId,
          secretLevel: this.secrecyGrade
        },
        cancelToken: this.deviceToken.token,
        noCommit: true
      }
      this.$store.dispatch('saveData', postData).then(() => {
        this.step = 6
      }).catch(() => {
        this.step = 5
      })
    }
  }
}
</script>

<style scoped lang="less">
  .upload_dialog {
    .step_two {
      width: 100%;
      .total_progress {
        margin: 20px 0;
        width: 100%;
        height: 20px;
        background-color: @mesBgDefault;
        border-radius: 2px;
        overflow: hidden;
        .current_progress {
          height: 20px;
          background: url(../../../../../assets/img/bg_loading.png) top left;
          background-size: 100%;
          font-size: 12px;
          color: @mesFontWhite;
          line-height: 20px;
          text-align: right;
        }
      }
    }
    .step_msg {
      height: 24px;
      padding: 20px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: #333;
      .step_msg_txt {
        height: 16px;
        line-height: 16px;
      }
      .icon-zhengquetishi {
        color: @mesFontSuccess;
        font-size: 24px;
        margin-right: 5px;
      }
      .icon-xiaoxitishi {
        font-size: 24px;
        margin-right: 5px;
      }
    }
    .step_four {
      height: 90px;
    }
    .step_three, .step_five {
      .step_msg {
        color: @mesFontRed;
      }
    }
  }
</style>
